﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
/// <summary>
/// 用于使用了particle shader等mat，挂载在Scrollview的子件上进行Clip
/// </summary>
[AddComponentMenu("Nirvana/Render/Particle Mask")]
public class ParticleMask : MonoBehaviour
{
    [SerializeField]
    private RectMask2D mask;
    [SerializeField] 
    private List<Material> mats;

    // Start is called before the first frame update
    void Start()
    {
        //粒子
        var allps = GetComponentsInChildren<ParticleSystem>(true);
        if (allps.Length > 0)
        {
            mats = new List<Material>();
            foreach (var p in allps)
            {
                var mat = p.GetComponent<Renderer>().material;
                if(mat != null) mats.Add(mat);
            }
        }

        //image
        var allimg = GetComponentsInChildren<Image>(true);
        if (allimg.Length > 0)
        {
            if(mats == null) mats = new List<Material>(allimg.Length);
            foreach (var p in allimg)
            {
                if (p.material == null) continue;
                var mat = p.material;
                mats.Add(mat);
            }
        }

        mask = GetComponentInParent<RectMask2D>();
        // ScrollView位置变化时重新计算裁剪区域
        GetComponentInParent<ScrollRect>().onValueChanged.AddListener((e) => { setClip(); });
        setClip();
    }
    void setClip()
    {
        Vector3[] wc = new Vector3[4];
        Shader shader = null;
        mask.GetComponent<RectTransform>().GetWorldCorners(wc);        // 计算world space中的点坐标
        var clipRect = new Vector4(wc[0].x, wc[0].y, wc[2].x, wc[2].y);// 选取左下角和右上角
        foreach(var mt in mats)
        {
            if (!mt.shader.name.StartsWith("Game/Particle"))
            {
                if(shader == null ) shader= Shader.Find("Game/Particle");
                mt.shader = shader;
            }
            if (mt.IsKeywordEnabled("ENABLE_UI_CLIP")) continue;
            mt.EnableKeyword("ENABLE_UI_CLIP");
            mt.SetVector("_ClipRect", clipRect);                           // 设置裁剪区域
        }
    }

    //private void OnDestroy()
    //{
    //    if(mats!= null)
    //    foreach (var mt in mats)
    //    {
    //        mt.DisableKeyword("ENABLE_UI_CLIP");
    //    }
    //}

}
